<template>
  <div style="margin: 10px 10px;">
    <el-card style="height: 640px; display: inline-block; width: 100%;">
      <!-- 菜单栏 -->
      <div class="top-tool-bar">
          <div style="float: left;">
            <el-button-group>
              <el-button :type="table.status === -1 ? 'success' : 'primary'" @click="changeData(-1)">全部</el-button>
              <el-button :type="table.status === 1 ? 'success' : 'primary'" @click="changeData(1)">已通过</el-button>
              <el-button :type="table.status === 2 ? 'success' : 'primary'" @click="changeData(2)">已退回</el-button>
              <el-button :type="table.status === 0 ? 'success' : 'primary'" @click="changeData(0)">待审批</el-button>
            </el-button-group>
          </div>
          <div style="float: right;">
            <el-button type="primary" icon="el-icon-circle-plus-outline" @click="createPlan()">制定采购计划</el-button>
          </div>
      </div>
      <!-- 表格 -->
      <div class="data-table">
        <el-table
          height="500"
          stripe
          highlight-current-row
          v-loading="table.loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          :data="purchaseList">
          <el-table-column label="id" prop="id" width="60"></el-table-column>
          <el-table-column label="申请人" min-width="100" :formatter="row => userMap.get(row.userId)"></el-table-column>
          <el-table-column label="部门" min-width="100" :formatter="() => department.name"></el-table-column>
          <el-table-column label="审批状态" min-width="100" :formatter="row => statusMap.get(row.status)"></el-table-column>
          <el-table-column label="申请金额/元" prop="applyFund" min-width="100"
            :formatter="r => $numeral(r.applyFund).format('0.00')"></el-table-column>
          <el-table-column label="批准金额/元" prop="approvalFund" min-width="100"
            :formatter="r => $numeral(r.approvalFund).format('0.00')"></el-table-column>
          <el-table-column label="申请时间" prop="applyTime" width="160"></el-table-column>
          <el-table-column label="审批时间" prop="approvalTime" width="160"></el-table-column>
          <el-table-column label="操作" width="160" fixed="right">
            <template slot-scope="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.status === 0">
                <el-button size="mini" type="primary" icon="el-icon-edit" circle @click="updatePlan(scope.row.id)"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button size="mini" type="danger" icon="el-icon-delete" circle @click="deletePlan(scope.row.id)"></el-button>
              </el-tooltip>
              <el-button size="mini" type="danger" icon="el-icon-more" circle @click="showDetail(scope.row.id, scope.row.status)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="bottom-page">
        <el-pagination
          background
          @size-change="selectPurchase()"
          @current-change="val => this.pagination.currentPage = val"
          :current-page="pagination.currentPage"
          :page-sizes="pagination.pageSizes" :page-size="pagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增/修改 -->
    <purchase-form
      :id="item.id"
      :show-dialog.sync="showDialog"
      :category-group="categoryGroup"
      :brand-map="brandMap"
      :category-map="categoryMap"
      :brands="brands"
      @success="selectPurchase()">
    </purchase-form>
    <!-- 查看详情/审批 -->
    <purchase-detail
      @success="selectPurchase()"
      :item="item"
      :show-detail-dialog.sync="showDetailDialog"
      :brand-map="brandMap"
      :category-map="categoryMap">
    </purchase-detail>
  </div>
</template>

<script>
import purchaseData from '@/data/purchaseData'
import statusMap from '@/data/approvalStatus'

import purchaseForm from '@/components/pages/purchase/PurchaseForm'
import purchaseDetail from '@/components/pages/purchase/PurchaseDetail.vue'

import * as brand from '@/api/brand'
import * as category from '@/api/category'
import * as purchase from '@/api/purchase'
import * as department from '@/api/department'
import * as user from '@/api/user'

export default {
  name: 'PurchaseInfo',
  data () {
    return {
      statusMap,
      purchaseList: purchaseData,
      department: {},
      brands: [],
      categorys: [],
      userMap: new Map(),
      pagination: {
        currentPage: 1,
        pageSize: 10,
        pageSizes: [10, 20]
      },
      item: {
        id: 0,
        status: -1
      },
      table: {
        loading: false,
        status: -1
      },
      showDialog: false,
      showDetailDialog: false
    }
  },
  watch: {
    pagination: {
      deep: true,
      handler: function () {
        this.selectPurchase()
      }
    }
  },
  created () {
    // 获取采购信息
    this.selectPurchase()
    // 获取部门信息
    department.selectById(this.$store.state.user.depaId).then(resp => {
      this.department = resp.data
    }).catch(() => {
      this.$notify.error('部门信息加载失败')
    })
    // 获取 brands、categorys 数据
    brand.selectAll().then(resp => {
      this.brands = resp.data.data
    }).catch(() => {
      this.$notify.error('品牌信息获取失败')
    })
    category.selectAll().then(resp => {
      this.categorys = resp.data.data
    }).catch(() => {
      this.$notify.error('分类信息获取失败')
    })
  },
  computed: {
    categoryGroup: function () {
      let baseGroup = this.categorys.filter(item => item.pid === 0)
      baseGroup.forEach(item => {
        item.children = this.categorys.filter(e => e.pid === item.id)
      })
      return baseGroup
    },
    brandMap: function () {
      let map = new Map()
      this.brands.forEach(e => { map.set(e.id, e.name) })
      return map
    },
    categoryMap: function () {
      let map = new Map()
      this.categorys.forEach(e => { map.set(e.id, e.name) })
      return map
    }
  },
  methods: {
    // 获取表格数据
    loadData (params) {
      // 查询采购信息
      purchase.selectByPage(params).then(resp => {
        let list = resp.data.data
        this.pagination.total = resp.data.total
        const set = new Set()
        list.forEach(e => { set.add(e.userId) })
        // 查询关联的用户信息
        user.selectByIds(set).then(resp => {
          let userList = resp.data
          userList.forEach(e => {
            this.userMap.set(e.id, e.username)
          })
          this.purchaseList = list
          this.table.loading = false
        })
      }).catch(() => {
        this.table.loading = false
        this.$notify.error('采购信息加载失败')
      })
    },
    // 分页查询采购单信息
    selectPurchase () {
      this.table.loading = true
      const params = {
        page: this.pagination.currentPage,
        rows: this.pagination.pageSize,
        depaId: this.$store.state.user.depaId
      }
      if (this.table.status !== -1) {
        params.status = this.table.status
      }
      // 获取数据
      this.loadData(params)
    },
    // 切换表格数据
    changeData (status) {
      this.table.status = status
      if (this.pagination.currentPage === 1) {
        // 未触发监听，手动调用查询
        this.selectPurchase()
      } else {
        // 触发监听
        this.pagination.currentPage = 1
      }
    },
    // 新建采购计划
    createPlan () {
      this.item.id = 0
      this.showDialog = true
    },
    // 更新采购计划
    updatePlan (id) {
      this.item.id = id
      this.showDialog = true
    },
    // 移除采购计划
    deletePlan (id) {
      purchase.remove(id).then(resp => {
        this.$notify.success('采购单已成功删除')
        // 刷新数据
        this.selectPurchase()
      }).catch(error => {
        if (error.response) {
          this.$notify.error(error.response.data.message || '删除失败')
        }
      })
    },
    // 查看采购详情
    showDetail (id, status) {
      this.item.id = id
      this.item.status = status
      this.showDetailDialog = true
    }
  },
  components: {
    purchaseForm,
    purchaseDetail
  }
}
</script>

<style scoped>
  .top-tool-bar {
    height: 56px;
  }
  .data-table {
    border: 1px gainsboro solid;
  }
  .bottom-page {
    height: 100%;
    margin: 10px auto;
  }
</style>
